import re
from flask import Blueprint, g, request, session, redirect
from flask.json import jsonify

from app import csrf
from ...app_1_0.auth.auth import login_require
from config import Config

user_bp = Blueprint('user', __name__)

from .views import register, login, logout, send_mail, user_list, \
    user_role_list, set_user_role, user_perm_list, user_perm_set


@user_bp.before_request
# @login_require
# @csrf.exempt
@csrf.exempt
def before_request():
    # user_id = g.user_id
    # user = User.query.filter_by(id=user_id).first()
    current_path = request.path
    # 1、放行白名单
    for w in Config.URL_WHITE_LIST:
        if re.match(w, current_path):
            return None
    # 2、session空时，请登录
    if not session['perms']:
        redirect('/login/')

    if request.path not in session['perms']:
        return jsonify({'code': 403, 'info': '无访问权限'})
    return None


@user_bp.after_request
def allow_cross_origin(response):
    """
    添加响应头部信息，解决前端访问跨域问题。
    :param response:
    :return:
    """
    # if response.headers.get('Content-Type').startswith('text'):
    #     response.headers['Content-Type'] = 'application/json'
    #     print("after_request......")

    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = "Referer,Accept,Origin,User-Agent,X-Requested-With,content-type"
    return response
